package com.apes.pi.parser;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.ApesParser;
import com.apes.framework.plugin.esb.api.Request;
import com.apes.framework.plugin.esb.processor.ChainProcessor;
import com.apes.framework.plugin.esb.processor.connector.http.HttpTransporter;
import com.apes.pi.model.PiConnector;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：PiConnector 解析器
 *
 * @author xul
 * @create 2019-11-09 17:25
 */
@Component
public class PiConnectorParser implements ApesParser<PiConnector, ChainProcessor> {

    @Override
    public ChainProcessor parse(PiConnector connector) {
        switch (connector.getProtocol().getCode()) {
            case "http/https":
                return createHttpTransporter(connector);
            default:
                throw new RuntimeException(String.format("协议:%s 未实现！", connector.getProtocol().getCode()));
        }
    }

    private ChainProcessor createHttpTransporter(PiConnector connector) {
        HttpTransporter transporter = new HttpTransporter() {

            @Override
            protected Object doProcess(Request data) {
                Map m;
                if (data.getData() instanceof String) {
                    m = data.getMap();
                } else if (data.getData() instanceof Map) {
                    m = (Map) data.getData();
                } else {
                    throw new RuntimeException(this.getClass() + "\n" + " 数据格式错误!");
                }

                if (m.containsKey("headers") && m.containsKey("body")) {
                    Map<String, String> headers = getHeaders();
                    if (headers == null) headers = new HashMap<>();
                    headers.putAll((Map<String, String>) m.get("headers"));
                    data.setData(m.get("body"));
                    setHeaders(headers);    // 重新设置 headers
                }
                String url = connector.getUrl();
                if (m.containsKey("methodUrl")) {
                    if (!url.endsWith("/")) url += "/";
                    url += m.get("methodUrl").toString();
                }

                if (m.get("params") != null) {
                    JSONObject paramJson = (JSONObject) m.get("params");
                    setReturnHeaders(paramJson.getBooleanValue("returnHeaders"));
                    if (paramJson.getString("action") != null) {
                        setAction(paramJson.getString("action"));
                    }

                }

                setUrl(url);
                return super.doProcess(data);
            }
        };
        Map<String, String> headers = new HashMap<>();
        connector.getParams().stream()
                .filter(param -> param.getCategory().getCode().equals("headers"))
                .forEach(param -> {
                    if ("responseType".equals(param.getType().getCode())) {
                        transporter.setResponseType(param.getValue());
                    } else {
                        headers.put(param.getType().getCode(), param.getValue());
                    }
                });
        if (!headers.isEmpty()) transporter.setHeaders(headers);
        return transporter;
    }
}
